package data;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import files.Files;

public class PhraseMark {

	private FileConnection fc;
	private InputStream fis;
	private OutputStream fos;
	private int phraseMark;

	public PhraseMark() throws IOException {
		String pageMarkFile = Files.getBookFolder() + "/PageMark.txt";
		fc = (FileConnection) Connector.open(pageMarkFile);

		if (!fc.exists()) {
			fc.create();
			fos = fc.openOutputStream();
			fos.write("0".getBytes());
			fos.close();
		}
		readPhraseMarkFromFile();
	}

	private void readPhraseMarkFromFile() throws IOException {
		byte[] b = new byte[20];
		fis = fc.openInputStream();
		int length = fis.read(b, 0, 20);
		fis.close();
		String raw = new String(b, 0, length);
		phraseMark = Integer.parseInt(raw);
	}

	public void increment(int increment) {
		phraseMark += increment;
	}

	public void decrement(int increment) {
		phraseMark -= increment;
		if (phraseMark < 0) {
			phraseMark = 0;
		}
	}

	public void save() throws IOException {
		fc.delete();
		fc.create();
		fos = fc.openOutputStream();
		fos.write(Integer.toString(phraseMark).getBytes());
		fos.close();
	}
	
	public int getMark() {
		return phraseMark;
	}

	public void setMark(int aMark) {
		phraseMark = aMark;
	}
}
